package core

import (
	"bytes"
	"fmt"
	"github.com/sirupsen/logrus"
	"os"
	"path"
	"software/global"
)

const (
	red    = 31
	yellow = 33
	blue   = 36
	gray   = 37
)

type LogFormatter struct {
}

func (t *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	var levelColor int
	switch entry.Level {
	case logrus.DebugLevel, logrus.TraceLevel:
		levelColor = gray
	case logrus.WarnLevel:
		levelColor = yellow
	case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
		levelColor = red
	default:
		levelColor = blue
	}

	var b *bytes.Buffer
	if entry.Buffer != nil {
		b = entry.Buffer
	} else {
		b = &bytes.Buffer{}
	}

	log := global.Config.Logger

	// 自定义日期格式
	timestamp := entry.Time.Format("2006-01-02 15:04:05")
	prefix := log.Prefix

	// 添加上下文字段（如额外的数据或标签）
	fields := ""
	for key, value := range entry.Data {
		fields += fmt.Sprintf(" %s=%v", key, value)
	}

	if entry.HasCaller() {
		funcVal := entry.Caller.Function
		fileVal := fmt.Sprintf("%s:%d", path.Base(entry.Caller.File), entry.Caller.Line)
		fmt.Fprintf(b, "%s [%s] \x1b[%dm[%s]\x1b[0m %s %s %s%s\n",
			prefix, timestamp, levelColor, entry.Level, fileVal, funcVal, entry.Message, fields)
	} else {
		fmt.Fprintf(b, "%s [%s] \x1b[%dm[%s]\x1b[0m %s%s\n",
			prefix, timestamp, levelColor, entry.Level, entry.Message, fields)
	}

	return b.Bytes(), nil
}

func InitLogger() *logrus.Logger {
	mblog := logrus.New()
	mblog.SetOutput(os.Stdout)
	mblog.SetReportCaller(true)
	mblog.SetFormatter(&LogFormatter{})
	mblog.SetLevel(logrus.DebugLevel)
	//InitDefaultLogger()

	return mblog
}

func InitDefaultLogger() {
	logrus.SetOutput(os.Stdout)
	logrus.SetReportCaller(true)
	logrus.SetFormatter(&LogFormatter{})
	logrus.SetLevel(logrus.DebugLevel)
}
